package com.sdx.console.content.web;

import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.ibeetl.admin.core.annotation.Function;
import com.ibeetl.admin.core.entity.CoreUser;
import com.ibeetl.admin.core.util.DateUtil;
import com.ibeetl.admin.core.util.ValidateConfig;
import com.ibeetl.admin.core.web.AuthorizedBaesController;
import com.ibeetl.admin.core.web.JsonResult;
import com.ibeetl.admin.core.web.JsonReturnCode;
import com.sdx.common.entity.ResCloudFile;
import com.sdx.common.service.ResCloudFileService;
import com.sdx.common.utils.FileUtils;
import com.sdx.common.utils.JacksonUtils;
import com.sdx.common.utils.Utils;
import com.sdx.console.content.entity.EbookChapter;
import com.sdx.console.content.service.EbookChapterService;
import com.sdx.service.ConfigService;
import com.sdx.third.AliOSSApi;
import org.beetl.sql.core.engine.PageQuery;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;


/**
 * 电子书章节 接口
 */
@RequestMapping("/content/ebookChapter")
@Controller
public class EbookChapterController extends AuthorizedBaesController{
	private static final Logger log = LoggerFactory.getLogger(EbookChapterController.class);
    private static final String MODEL = "/content/ebookChapter";

    @Resource
    ResCloudFileService resCloudFileService;

    @Resource
	private EbookChapterService ebookChapterService;

	/**
	 * 初始化页面需要的列表数据，
	 *
	 */
	private void setPageParam(ModelAndView view,Integer bookId) {
	    List<EbookChapter> pChapterIdList = new ArrayList<EbookChapter>();
        pChapterIdList =  ebookChapterService.listChapterByBookId(bookId);

        view.addObject("bookId",bookId);
        view.addObject("pChapterIdList",pChapterIdList);

	}

    /* 页面 */

    @GetMapping("/index.do")
    @Function("content.ebookChapter.query")
    @ResponseBody
    public ModelAndView index(Integer bookId) {
        ModelAndView view = new ModelAndView(MODEL+"/index.html") ;
		setPageParam(view,bookId);
        return view;
    }

    @GetMapping("/edit.do")
    @Function("content.ebookChapter.edit")
    @ResponseBody
    public ModelAndView edit(HttpServletRequest request,Integer chapterId) {
        ModelAndView view = new ModelAndView(MODEL+"/add.html");
        EbookChapter ebookChapter = ebookChapterService.queryById(chapterId);
        view.addObject("ebookChapter", ebookChapter);
		setPageParam(view,ebookChapter.getBookId());
		try {
			view.addObject("ebookChapterJson", JacksonUtils.toJsonString(ebookChapter,JacksonUtils.DF1));
		} catch (JsonProcessingException e) {
			e.printStackTrace();
		}
        return view;
    }

    @GetMapping("/add.do")
    @Function("content.ebookChapter.add")
    @ResponseBody
    public ModelAndView add(Integer bookId) {
        ModelAndView view = new ModelAndView(MODEL+"/add.html");
        view.addObject("ebookChapter", new EbookChapter());
		setPageParam(view,bookId);
        return view;
    }

    /* ajax json */

    @PostMapping("/list.json")
    @Function("content.ebookChapter.query")
    @ResponseBody
    public JsonResult<PageQuery> list(EbookChapter condtion)
    {
        PageQuery page = condtion.getPageQuery();
        if(condtion.getBookId()!=null){
            ebookChapterService.queryByCondition(page);
        }
        return JsonResult.success(page);
    }

    private JsonResult save(boolean isNew,EbookChapter ebookChapter,HttpServletRequest request,MultipartFile urlFile
	) {
    	JsonResult result = JsonResult.success();
		String dir = DateUtil.now("yyyyMMdd");
    	String subPath = "/images/ebook/chapter/"+ebookChapter.getBookId()+"/";
		String bucketName = "sdxcomm";
        if (!FileUtils.isEmptyFile(urlFile)) {
            try{
                String coverFileNamePair = FileUtils.upload(subPath,urlFile);
                String coverStoreFile = coverFileNamePair.split("::")[0];
                coverStoreFile = subPath+coverStoreFile;
                AliOSSApi.uploadLocalFile(FileUtils.getRoot()+coverStoreFile,bucketName,coverStoreFile.substring(1));
                String coverUrl = "https://sdxcomm."+ ConfigService.ossDomain+coverStoreFile;
                ebookChapter.setUrl(coverUrl);
                resCloudFileService.insertResFile(ResCloudFile.ALI,coverStoreFile,coverUrl,"f","章节地址");
            }catch(Exception e) {
                e.printStackTrace();
                result.setCode(JsonReturnCode.IO_ERROR.getCode());
                result.setMsg(e.getMessage());
            }
        }
		CoreUser user = getLoginUser(request);
		if(ebookChapter.getPChapterId()==null){
            ebookChapter.setPChapterId(0);
        }
    	if (isNew) {
			ebookChapter.setCreatedBy(user.getId().intValue());
			ebookChapter.setCreatedName(user.getName());
			ebookChapter.setCreatedTime(new Date());
			ebookChapter.setUpdatedBy(user.getId().intValue());
			ebookChapter.setUpdatedName(user.getName());
			ebookChapter.setUpdatedTime(new Date());
			ebookChapterService.save(ebookChapter);
		} else {
			ebookChapter.setUpdatedBy(user.getId().intValue());
			ebookChapter.setUpdatedName(user.getName());
			ebookChapter.setUpdatedTime(new Date());
			ebookChapterService.updateTemplate(ebookChapter);
		}
		return result;
	}
    @PostMapping("/add.json")
    @Function("content.ebookChapter.add")
    @ResponseBody
    public JsonResult add(@Validated(ValidateConfig.ADD.class)EbookChapter ebookChapter,HttpServletRequest request
            ,@RequestParam("urlFile") MultipartFile urlFile)
    {

        return save(true,ebookChapter,request,urlFile);
    }

    @PostMapping("/update.json")
    @Function("content.ebookChapter.edit")
    @ResponseBody
    public JsonResult<String> update(@Validated(ValidateConfig.UPDATE.class)  EbookChapter ebookChapter,HttpServletRequest request
            ,@RequestParam("urlFile") MultipartFile urlFile) {
		return save(false,ebookChapter,request,urlFile);
    }


   
    @GetMapping("/view.json")
    @Function("content.ebookChapter.query")
    @ResponseBody
    public JsonResult<EbookChapter>queryInfo(Integer chapterId) {
        EbookChapter ebookChapter = ebookChapterService.queryById( chapterId);
        return  JsonResult.success(ebookChapter);
    }

    @PostMapping("/delete.json")
    @Function("content.ebookChapter.del")
    @ResponseBody
    public JsonResult delete(String ids) {
		List<String> idList = Utils.strToList(ids,",");
        ebookChapterService.batchDelEbookChapter(idList);
        return JsonResult.success();
    }


    /**
     *  图片上传
     * @param upfile
     * @return
     */
    @RequestMapping("/upload.json")
    @ResponseBody
    public JSONObject uploadImg(MultipartFile upfile) {
        JSONObject jsobject = new JSONObject();
        String dir = DateUtil.now("yyyyMMdd");
        String subPath = "/images/plate/"+dir+"/";
        String bucketName = "sdxcomm";
        if (!FileUtils.isEmptyFile(upfile)) {
            try
            {
                String fileNamePair = FileUtils.upload(subPath,upfile);
                String storeFile = fileNamePair.split("::")[0];
                storeFile = subPath+storeFile;
                AliOSSApi.uploadLocalFile(FileUtils.getRoot()+storeFile,bucketName,storeFile.substring(1));
                String url = "https://sdxcomm."+ ConfigService.ossDomain+storeFile;
                jsobject.put("url",url);
                jsobject.put("state", "SUCCESS");
                jsobject.put("title", "");
                jsobject.put("original", "");
                resCloudFileService.insertResFile(ResCloudFile.ALI,storeFile,url,"a","电子书");
            }catch(Exception e) {
                e.printStackTrace();
                jsobject.put("state", "FAIL");
                jsobject.put("title", "");
                jsobject.put("original", "");
                jsobject.put("url","");
            }
        }
        return jsobject;
    }

    /**
     * 返回 ueditor 图片上传的配置参数
     * @return
     */
    @RequestMapping("/config")
    @ResponseBody
    public String config(){
         String UEDITOR_CONFIG = "{\n" +
                "    \"imageActionName\": \"uploadimage\",\n" +
                "    \"imageFieldName\": \"upfile\",\n" +
                "    \"imageAllowFiles\": [\".png\", \".jpg\", \".jpeg\", \".gif\", \".bmp\"],\n" +
                "    \"imageCompressEnable\": true,\n" +
                "    \"imageCompressBorder\": 1600,\n" +
                "    \"imageInsertAlign\": \"none\",\n" +
                "    \"imageUrlPrefix\": \"\",\n" +
                "    \"imagePathFormat\": \"/ueditor/jsp/upload/image/{yyyy}{mm}{dd}/{time}{rand:6}\",\n" +
                "\n" +
                "    \"scrawlActionName\": \"uploadscrawl\",\n" +
                "    \"scrawlFieldName\": \"upfile\",\n" +
                "    \"scrawlPathFormat\": \"/ueditor/jsp/upload/image/{yyyy}{mm}{dd}/{time}{rand:6}\",\n" +

                "    \"scrawlUrlPrefix\": \"\",\n" +
                "    \"scrawlInsertAlign\": \"none\",\n" +
                "\n" +
                "    \"snapscreenActionName\": \"uploadimage\",\n" +
                "    \"snapscreenPathFormat\": \"/ueditor/jsp/upload/image/{yyyy}{mm}{dd}/{time}{rand:6}\",\n" +
                "    \"snapscreenUrlPrefix\": \"\",\n" +
                "    \"snapscreenInsertAlign\": \"none\",\n" +
                "\n" +
                "    \"catcherLocalDomain\": [\"127.0.0.1\", \"localhost\", \"img.baidu.com\"],\n" +
                "    \"catcherActionName\": \"catchimage\",\n" +
                "    \"catcherFieldName\": \"source\",\n" +
                "    \"catcherPathFormat\": \"/ueditor/jsp/upload/image/{yyyy}{mm}{dd}/{time}{rand:6}\",\n" +
                "    \"catcherUrlPrefix\": \"\",\n" +
                "    \"catcherMaxSize\": 2048000,\n" +
                "    \"catcherAllowFiles\": [\".png\", \".jpg\", \".jpeg\", \".gif\", \".bmp\"],\n" +
                "\n" +
                "    \"videoActionName\": \"uploadvideo\",\n" +
                "    \"videoFieldName\": \"upfile\",\n" +
                "    \"videoPathFormat\": \"/ueditor/jsp/upload/video/{yyyy}{mm}{dd}/{time}{rand:6}\",\n" +
                "    \"videoUrlPrefix\": \"\",\n" +
                "    \"videoMaxSize\": 102400000,\n" +
                "    \"videoAllowFiles\": [\n" +
                "        \".flv\", \".swf\", \".mkv\", \".avi\", \".rm\", \".rmvb\", \".mpeg\", \".mpg\",\n" +
                "        \".ogg\", \".ogv\", \".mov\", \".wmv\", \".mp4\", \".webm\", \".mp3\", \".wav\", \".mid\"],\n" +
                "\n" +
                "    \"fileActionName\": \"uploadfile\",\n" +
                "    \"fileFieldName\": \"upfile\",\n" +
                "    \"filePathFormat\": \"/ueditor/jsp/upload/file/{yyyy}{mm}{dd}/{time}{rand:6}\",\n" +
                "    \"fileUrlPrefix\": \"\",\n" +
                "    \"fileMaxSize\": 51200000,\n" +
                "    \"fileAllowFiles\": [\n" +
                "        \".png\", \".jpg\", \".jpeg\", \".gif\", \".bmp\",\n" +
                "        \".flv\", \".swf\", \".mkv\", \".avi\", \".rm\", \".rmvb\", \".mpeg\", \".mpg\",\n" +
                "        \".ogg\", \".ogv\", \".mov\", \".wmv\", \".mp4\", \".webm\", \".mp3\", \".wav\", \".mid\",\n" +
                "        \".rar\", \".zip\", \".tar\", \".gz\", \".7z\", \".bz2\", \".cab\", \".iso\",\n" +
                "        \".doc\", \".docx\", \".xls\", \".xlsx\", \".ppt\", \".pptx\", \".pdf\", \".txt\", \".md\", \".xml\"\n" +
                "    ],\n" +
                "\n" +
                "    \"imageManagerActionName\": \"listimage\",\n" +
                "    \"imageManagerListPath\": \"/ueditor/jsp/upload/image/\",\n" +
                "    \"imageManagerListSize\": 20,\n" +
                "    \"imageManagerUrlPrefix\": \"\",\n" +
                "    \"imageManagerInsertAlign\": \"none\",\n" +
                "    \"imageManagerAllowFiles\": [\".png\", \".jpg\", \".jpeg\", \".gif\", \".bmp\"],\n" +
                "\n" +
                "    \"fileManagerActionName\": \"listfile\",\n" +
                "    \"fileManagerListPath\": \"/ueditor/jsp/upload/file/\",\n" +
                "    \"fileManagerUrlPrefix\": \"\",\n" +
                "    \"fileManagerListSize\": 20,\n" +
                "    \"fileManagerAllowFiles\": [\n" +
                "        \".png\", \".jpg\", \".jpeg\", \".gif\", \".bmp\",\n" +
                "        \".flv\", \".swf\", \".mkv\", \".avi\", \".rm\", \".rmvb\", \".mpeg\", \".mpg\",\n" +
                "        \".ogg\", \".ogv\", \".mov\", \".wmv\", \".mp4\", \".webm\", \".mp3\", \".wav\", \".mid\",\n" +
                "        \".rar\", \".zip\", \".tar\", \".gz\", \".7z\", \".bz2\", \".cab\", \".iso\",\n" +
                "        \".doc\", \".docx\", \".xls\", \".xlsx\", \".ppt\", \".pptx\", \".pdf\", \".txt\", \".md\", \".xml\"\n" +
                "    ] \n" +
                "\n" +
                "}";
         return UEDITOR_CONFIG;
    }
    

}
